#!/bin/bash


mstack_script_dir=$(dirname "$(realpath "${BASH_SOURCE[0]}")")
source $mstack_script_dir/common_variables.sh


function synchronization_package() {
    echo
    echo "------"
    echo -e "${BLUE}$ip $name 缓存docker软件包${NC}"
    rsync -avz $mstack_packet_archives_dir/ $ip:/var/cache/apt/archives/
    echo -e "${GREEN}$ip $name Docker 安装包已同步到缓存目录。${NC}"
}

reinstall_podman() {
    # 定义要删除的 Podman 相关服务
    services_to_remove=(
        "podman"
        "podman-plugins"
        "podman-docker"
        "podman-build"
        "podman-compose"
    )

    # 开始删除 Podman 及其依赖
    echo -e "${RED}正在删除 $name 上 Podman 及其依赖...${NC}"
    failed_removals=()

    for service in "${services_to_remove[@]}"; do
        echo -e "${YELLOW}正在删除 $name 服务 : $service${NC}"
        ssh $ip sudo apt-get remove --purge -y "$service"
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}$name 服务 $service 删除成功！${NC}"
        else
            echo -e "${RED}$name 服务 $service 删除失败！${NC}"
            failed_removals+=("$service")
        fi
    done

    # 检查失败的删除操作
    if [ ${#failed_removals[@]} -ne 0 ]; then
        echo -e "${RED}$name 服务以下服务未能成功删除:${NC}"
        for failed_service in "${failed_removals[@]}"; do
            echo -e "${RED}- $failed_service${NC}"
        done
        echo -e "${YELLOW}请手动检查并删除这些服务。${NC}"
    else
        echo -e "${GREEN}所有指定的 Podman 相关服务均已成功删除！${NC}"
    fi

}
remove_podman() {
    echo -e "${BLUE}检查主机: $name ($ip)是否安装podman{NC}"

    # 检查 Docker 是否安装
    if ssh "$ip" "command -v podman &> /dev/null"; then
        echo -e "${YELLOW}$name 上已安装 podman, 正在卸载${NC}"
        reinstall_podman
    else
        echo -e "${YELLOW}$name 上未安装 podman，跳过卸载。${NC}"
    fi

    echo -e "${BLUE}----------------------------------------------------------------${NC}"
}



install_docker() {
    echo -e "${BLUE}处理主机: $name ($ip)${NC}"

    # 检查 Docker 是否安装
    if ssh "$ip" "command -v docker &> /dev/null"; then
        echo -e "${YELLOW}$name 上已安装 Docker。${NC}"
        prompt_reinstall_docker
    else
        echo -e "${YELLOW}$name 上未安装 Docker，将进行安装。${NC}"
        install_docker_packages
    fi

    echo -e "${BLUE}----------------------------------------------------------------${NC}"
}

prompt_reinstall_docker() {
    read -p "是否重新安装 Docker？(y/n): " reinstall
    if [ "$reinstall" == "y" ]; then
        reinstall_docker
    else
        echo -e "${YELLOW}跳过重新安装。${NC}"
    fi
}

reinstall_docker() {
    # 定义要删除的 Docker 相关服务
    services_to_remove=(
        "docker-ce"
        "docker-ce-cli"
        "containerd.io"
        "docker-compose-plugin"
        "docker-ce-rootless-extras"
        "docker-buildx-plugin"
    )

    # 开始删除 Docker 及其依赖
    echo -e "${RED}正在删除 $name 上 Docker 及其依赖...${NC}"
    failed_removals=()

    for service in "${services_to_remove[@]}"; do
        echo -e "${YELLOW}正在删除 $name 服务 : $service${NC}"
        ssh $ip sudo apt-get remove --purge -y "$service"
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}$name 服务 $service 删除成功！${NC}"
        else
            echo -e "${RED}$name 服务 $service 删除失败！${NC}"
            failed_removals+=("$service")
        fi
    done

    # 检查失败的删除操作
    if [ ${#failed_removals[@]} -ne 0 ]; then
        echo -e "${RED}$name 服务以下服务未能成功删除:${NC}"
        for failed_service in "${failed_removals[@]}"; do
            echo -e "${RED}- $failed_service${NC}"
        done
        echo -e "${YELLOW}请手动检查并删除这些服务。${NC}"
    else
        echo -e "${GREEN}所有指定的 Docker 相关服务均已成功删除！${NC}"
    fi

    # 安装 Docker
    install_docker_packages
}

install_docker_packages() {
    echo -e "${BLUE}开始安装 Docker 相关服务...${NC}"

    packages=(
        "containerd.io_1.7.22-1_amd64.deb"
        "docker-ce-cli_27.3.1-1~ubuntu.22.04~jammy_amd64.deb"
        "docker-buildx-plugin_0.17.1-1~ubuntu.22.04~jammy_amd64.deb"
        "docker-ce-rootless-extras_27.3.1-1~ubuntu.22.04~jammy_amd64.deb"
        "docker-ce_27.3.1-1~ubuntu.22.04~jammy_amd64.deb"
        "docker-compose-plugin_2.27.1-1~ubuntu.22.04~jammy_amd64.deb"
    )
    failed_packages=()

    for package in "${packages[@]}"; do
        echo -e "${YELLOW}$name 开始安装: $package${NC}"
        echo "sudo dpkg -i /var/cache/apt/archives/$package"
        ssh "$ip" "sudo dpkg -i /var/cache/apt/archives/$package"
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}$name $package 安装成功！${NC}"
        else
            echo -e "${RED}$name $package 安装失败！${NC}"
            failed_packages+=("$package")
        fi
    done

    # 检查并重试失败的安装包
    if [ ${#failed_packages[@]} -ne 0 ]; then
        echo -e "${RED}$name 以下软件包未能成功安装:${NC}"
        for failed_pkg in "${failed_packages[@]}"; do
            echo -e "${RED}- $failed_pkg${NC}"
        done
        read -p "是否重新尝试安装失败的软件包？(y/n): " retry
        if [ "$retry" == "y" ]; then
            for failed_pkg in "${failed_packages[@]}"; do
                echo -e "${YELLOW}重新安装: $failed_pkg${NC}"
                ssh "$ip" "sudo dpkg -i /var/cache/apt/archives/$failed_pkg"
                if [ $? -eq 0 ]; then
                    echo -e "${GREEN}$failed_pkg 重新安装成功！${NC}"
                else
                    echo -e "${RED}$failed_pkg 再次安装失败，请手动检查！${NC}"
                fi
            done
        else
            echo -e "${YELLOW}跳过失败的安装包，请手动检查后安装。${NC}"
        fi
    else
        echo -e "${GREEN}所有 Docker 相关软件包已成功安装！${NC}"
    fi

    # 启动并设置 Docker 服务开机自启
    echo -e "${BLUE}启动并设置 Docker 开机自启...${NC}"
    ssh "$ip" "sudo systemctl start docker"
    ssh "$ip" "sudo systemctl enable docker"
    ssh "$ip" "sudo systemctl restart docker"
    sleep 2

    # 检查 Docker 服务状态
    if ssh "$ip" "sudo systemctl is-active --quiet docker"; then
        echo
        echo
        echo -e "${BLUE}检查 $name ($ip) 上的 Docker 容器状态...${NC}"
        ssh "$ip" "docker ps -a"
        echo -e "${GREEN}Docker 在 $name 上运行正常！${NC}"
    else
        echo -e "${RED}Docker 在 $name 上启动失败，请检查日志！${NC}"
    fi
    sleep 3
    ssh "$ip" "pids=$(pgrep -f 'apt|dpkg-preconfigure')"
    ssh "$ip" echo "$pids" | xargs -r sudo kill -9
}


echo "--------------------------------------------------"

# 读取 hosts 文件并处理
for ip in $(awk '{print $1}' $mstack_tools_mstack_dir/mstack_all_nodes.txt | sed -r '/^[ \t]*($|#)/d'); do
    # 通过 grep 获取对应的主机名
    name=$(grep "$ip" $mstack_tools_mstack_dir/mstack_all_nodes.txt| awk '{print $2}' | sed -r '/^[ \t]*($|#)/d')

    remove_podman
    synchronization_package
    install_docker

done
